package com.hifar.httpclient.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * HTTP客户 端服务类
 *
 * @author : maiti
 * @date : 2025/2/10 10:40
 */
@Service
public class WebClientService {

	@Autowired
	private WebClient.Builder webClientBuilder;

	public Mono<String> sendGetRequest(String url) {
		return webClientBuilder.baseUrl(url).build().get().retrieve().bodyToMono(String.class);
	}

	public Mono<String> sendPostRequest(String url, Object requestPayload) {
		WebClient webClient = webClientBuilder.baseUrl(url)
				.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();

		Mono<String> stringMono = webClient.post().bodyValue(requestPayload).retrieve().bodyToMono(String.class);
		return stringMono;

	}

	public String sendPostRequestSync(String url, Object requestPayload) {
		WebClient webClient = webClientBuilder.baseUrl(url)
				.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();

		String response = webClient.post().bodyValue(requestPayload).retrieve().bodyToMono(String.class).block();

		return response;

	}

}
